import Icon from '@/components/Icon';
import { View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import classNames from 'classnames';
import React, { useMemo } from 'react';
import { noop } from '@/utils/fn';
import { BarPosition } from './constants';
import styles from './index.module.scss';

/**
 * @param {object} props
 * @param {string|undefined} props.className CustomNavBar 的 className
 * @param {boolean} props.style        自定义覆盖样式
 *
 * @param {'default' | 'suspended' | 'hidden'} props.position         默认无左边返回按钮
 * @param {boolean} props.back         默认无左边返回按钮
 * @param {boolean} props.backBlock    默认无左边菜单占据的距离
 * @param {boolean} props.menuBlock    默认无右边菜单占据的距离
 * @param {boolean} props.sticky       默认sticky布局
 * @param {any[]} props.children       title不存在时, 渲染children
 */
const CustomNavBar = ({
  back = false,

  backBlock = !!back,
  menuBlock = false,
  className = '',
  position = BarPosition.default,
  style = {},

  // 整个顶部点击
  onClick = noop,
  // 返回按钮点击
  onBackClick = (_e, isBack) => {
    if (isBack) {
      Taro.navigateBack();
    }
  },
  // 右侧微信原生menu外边框内的点击, 无法覆盖原生menu事件
  onMenuClick = onClick,

  children,
}) => {
  const isAndroid = Taro.$platform === 'android';

  const extra = useMemo(() => {
    if (position === 'default') {
      return {
        position: 'sticky',
        top: 0,
        zIndex: 999,
      };
    }

    if (position === 'suspended') {
      return {
        position: 'absolute',
        top: 0,
        left: 0,
        zIndex: 999,
      };
    }

    if (position === 'hidden') {
      return {
        display: 'none',
      };
    }

    return {};
  }, [position]);

  return (
    <View
      className={classNames(`${styles.CustomNavBar} ${className}`, {
        'force-hidden': Taro.$statusBarHeight + Taro.$titleHeight === 0,
      })}
      onClick={onClick}
      style={{
        paddingTop: Taro.$statusBarHeight + 'px',
        paddingBottom: Taro.$navBarExtendHeight + 'px',
        height: Taro.$titleHeight,
        ...extra,
        ...style,
      }}
    >
      {/* 左边返回按钮和展示的距离 */}
      {backBlock && (
        <View
          className={classNames('left', { android: isAndroid, 'no-back': !back })}
          onClick={(e) => {
            if (onBackClick) {
              onBackClick(e, back);
            }
          }}
        >
          {back && (
            <Icon
              className="icon"
              name="a-tubiaoai_huaban2fuben9"
              size={30}
              color={'#ff0d49'}
            />
          )}
        </View>
      )}

      {/* 标题栏展示的内容 */}
      {children}

      {/* 右边菜单占据的距离 */}
      {menuBlock && (
        <View
          className={classNames('right', {
            [Taro.$platform]: true,
          })}
          onClick={onMenuClick}
        ></View>
      )}
    </View>
  );
};

export default CustomNavBar;
